package parse

import (
	"Crawlab/common/engine/os"
	"Crawlab/common/model"
	"regexp"
	"strconv"
)

// 0 完整内容
// 1 用户连接
// 2 用户名称
// 3 帖子连接
// 4 帖子标题
// 5 点击数
// 6 发帖时间
// 7 发帖所属版块连接
// 8 发帖所属版块名称
// 9 已有回复数
const forumRegexpTemplate = `<li>[^<]+<div class="topic-anchor">[^<]+<a href="(user\.info\.[\d]+\.html)">[^<]+<img src="[^"]+" class="avatar">[^<]+</a>[^<]+<a href="user\.info\.[\d]+\.html">([^<]+)</a>[^<]+</div>[^<]+<div class="topic-title">[^<]+<a href="(bbs\.topic\.[\d]+\.html)">([^<]+)</a>[^<]+<div class="topic-meta">[\s]*([\d]+)点击 / [\s]*([^<]+)</div>[^<]+</div>[^<]+<div class="topic-forum-name">[^<]+<a href="(bbs\.forum\.[\d]+\.html)" class="topic-title">([^<]+)</a>[^<]+</div>[^<]+<div class="topic-reply-count">[^<]+<a href="bbs\.topic\.[\d]+\.html">([\d]+)</a>[^<]+</div>[^<]+</li>`

var forumRegexp = regexp.MustCompile(forumRegexpTemplate)

// 帖子匹配结果
func ForumParseResult(content []byte) os.ParseResult {
	matchArray := forumRegexp.FindAllStringSubmatch(string(content), -1)

	parseResult := os.ParseResult{}

	var postArray []model.Post
	for _, value := range matchArray {
		clickNumber, _ := strconv.Atoi(value[5])
		commentsNumber, _ := strconv.Atoi(value[9])
		post := model.Post{
			UserLink:       value[1],
			UserName:       value[2],
			PostLink:       value[3],
			PostTitle:      value[4],
			ClickNumber:    clickNumber,
			PostingTime:    value[6],
			ForumLink:      value[7],
			ForumName:      value[8],
			CommentsNumber: commentsNumber,
		}
		postArray = append(postArray, post)
		parseResult.Items = append(parseResult.Items, "Post "+post.PostTitle+",  Url: https://hu60.cn/q.php/"+post.PostLink)
		parseResult.Requests = append(parseResult.Requests, os.Request{
			// Url:       "https://hu60.cn/q.php/" + post.PostLink,
			Url:       "",
			ParseFunc: os.NilParseFunc,
		})
	}

	return parseResult
}
